﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SEO.Utility
{
    public class XmlHelper
    {
        private XmlDocument xmlDoc = null;



        public XmlHelper()
        {

            xmlDoc = new XmlDocument();

        }

        /// <summary>

        /// 加载xml文件

        /// </summary>

        /// <param name="fileName">xml 文件路径</param>
        public void Load(string fileName)
        {

            xmlDoc.Load(fileName);

        }



        /// <summary>

        /// 读取xml内容

        /// </summary>

        /// <param name="xml">xml 内容</param>

        public void LoadXml(string xml)
        {

            xmlDoc.LoadXml(xml);

        }



        /// <summary>

        /// xpath 是否存在

        /// </summary>

        /// <param name="xpath">xpath 路径</param>

        /// <returns></returns>

        public bool IsExists(string xpath)
        {

            return xmlDoc.DocumentElement.SelectSingleNode(xpath) != null ? true : false;

        }



        /// <summary>

        /// xpath 是否存在

        /// </summary>

        /// <param name="xn">节点</param>

        /// <param name="xpath">xpath 路径</param>

        /// <returns></returns>

        public bool IsExists(XmlNode xn, string xpath)
        {

            return xn.SelectSingleNode(xpath) != null ? true : false;

        }

        /// <summary>

        /// 选择指定节点

        /// </summary>

        /// <param name="xpath">xpath 路径</param>

        /// <returns></returns>

        public XmlNodeList SelectNodes(string xpath)
        {

            return xmlDoc.DocumentElement.SelectNodes(xpath);

        }



        /// <summary>

        /// 选择指定节点

        /// </summary>

        /// <param name="xn">节点</param>

        /// <param name="xpath">xpath 路径</param>

        /// <returns></returns>

        public XmlNodeList SelectNodes(XmlNode xn, string xpath)
        {

            return xn.SelectNodes(xpath);

        }



        /// <summary>

        /// 选择单节点

        /// </summary>

        /// <param name="xpath">xpath 路径</param>

        /// <returns></returns>

        public string SelectSingleNode(string xpath)
        {

            return IsExists(xpath) ? xmlDoc.DocumentElement.SelectSingleNode(xpath).InnerText : string.Empty;

        }



        /// <summary>

        /// 选择单节点

        /// </summary>

        /// <param name="xn">节点</param>

        /// <param name="xpath">xpath 路径</param>

        /// <returns></returns>

        public string SelectSingleNode(XmlNode xn, string xpath)
        {

            return IsExists(xn, xpath) ? xn.SelectSingleNode(xpath).InnerText : string.Empty;

        }
    }
}
